﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace V5_Apps.Plugins.Qvod._Class {
    public class HttpHelper {

        private static readonly HttpHelper m_Instance = new HttpHelper();
        /// <summary>
        /// 
        /// </summary>
        public static HttpHelper Instance {
            get { return m_Instance; }
        }

        /// <summary>
        /// 获取快播地址
        /// </summary>
        /// <param name="urls"></param>
        /// <returns></returns>
        public string getQvodUrls(string urls) {
            string str = "";
            List<string> list = new List<string>();
            foreach (Match match in Regex.Matches(urls, @"((http://[^/]*?/[\d]*/[\w]{40}/[\s\S]*?\.(rmvb|mkv|wmv|rm|avi|asf|mov|mpg|mpeg|torrent|3gp|mp4|ram|flv|mpe|mpeg4|dvd|qmv))|(qvod://[\d]*\|[\w]{40}\|[\s\S]*?\.(rmvb|mkv|wmv|rm|avi|asf|mov|mpg|mpeg|torrent|3gp|mp4|ram|flv|mpe|mpeg4|dvd|qmv)\|?))", RegexOptions.IgnoreCase)) {
                string str2 = Regex.Unescape(match.Groups[1].Value.Trim());
                if (!string.IsNullOrEmpty(str2)) {
                    if (Regex.IsMatch(str2, @"^qvod://[\d]+\|[\w]{40}\|.*?\.(rmvb|mkv|wmv|rm|avi|asf|mov|mpg|mpeg|torrent|3gp|mp4|ram|flv|mpe|mpeg4|dvd|qmv)\|?$", RegexOptions.IgnoreCase) && (checkInArray(list, str2) == -1)) {
                        str = str + str2.Trim().Replace(";", "") + ";";
                        list.Add(str2);
                    }
                    else if (Regex.IsMatch(str2, @"^http://[^/]*?/[\d]+/[\w]{40}/[\s\S]*?\.(rmvb|mkv|wmv|rm|avi|asf|mov|mpg|mpeg|torrent|3gp|mp4|ram|flv|mpe|mpeg4|dvd|qmv)$", RegexOptions.IgnoreCase) && (checkInArray(list, str2) == -1)) {
                        str = str + str2.Trim().Replace(";", "") + ";";
                        list.Add(str2);
                    }
                }
            }
            return str;
        }


        public int checkInArray(List<string> list, string url) {
            for (int i = 0; i < list.Count; i++) {
                if (url.ToLower() == list[i].ToLower()) {
                    return i;
                }
            }
            return -1;
        }


        /// <summary>
        /// 自动获取网页内容  $UrlIsFalse$    $GetFalse$
        /// </summary>
        public string GetHttpPage(string url, ref string encode, int timeout) {
            string strResult = string.Empty;
            if (url.Length < 10)
                return "$UrlIsFalse$";
            try {
                WebClient wc = new WebClient(); //创建WebClient实例myWebClient
                wc.Credentials = CredentialCache.DefaultCredentials;
                byte[] myDataBuffer = wc.DownloadData(url);
                string strWebData = Encoding.Default.GetString(myDataBuffer);
                if (string.IsNullOrEmpty(encode)) {
                    Match charSetMatch = Regex.Match(strWebData, "<meta([^<]*)charset=([^<]*)\"", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    encode = charSetMatch.Groups[2].Value;
                }
                strWebData = Encoding.GetEncoding(encode).GetString(myDataBuffer);

                strResult = strWebData;
            }
            catch (Exception ex) {
                strResult = "$GetFalse$";
            }
            return strResult;
        }



        /// <summary>
        /// 格式化地址
        /// </summary>
        /// <param name="BaseUrl">http://www.v5soft.com</param>
        /// <param name="theUrl">/index.html</param>
        /// <returns></returns>
        public string FormatUrl(string BaseUrl, string theUrl) {
            int pathLevel = 0;
            string hostName;
            theUrl = theUrl.ToLower();
            hostName = BaseUrl.Substring(0, BaseUrl.IndexOf("/", 8));
            BaseUrl = BaseUrl.Substring(0, BaseUrl.LastIndexOf("/"));
            if (theUrl.StartsWith("./")) {
                theUrl = theUrl.Remove(0, 1);
                theUrl = BaseUrl + theUrl;
            }
            else if (theUrl.StartsWith("/")) {
                theUrl = hostName + theUrl;
            }
            else if (theUrl.StartsWith("../")) {
                while (theUrl.StartsWith("../")) {
                    pathLevel = ++pathLevel;
                    theUrl = theUrl.Remove(0, 3);
                }
                for (int i = 0; i < pathLevel; i++) {
                    BaseUrl = BaseUrl.Substring(0, BaseUrl.LastIndexOf("/", BaseUrl.Length - 2));
                }
                theUrl = BaseUrl + "/" + theUrl;
            }
            if (!theUrl.StartsWith("http://") && !theUrl.StartsWith("https://")) {
                theUrl = BaseUrl + "/" + theUrl;
            }
            return theUrl;
        }
    }
}
